#!/usr/bin/php
<?php

function main($argc, & $argv)
{
    if ($argc < 2) {
        fprintf(STDERR, "必须指定用户名!\n");
        return 0;
    }

    if (posix_geteuid() != 0) {
        fprintf(STDERR, "必须root权限执行!\n");
        return 0;
    }

    if (($user = posix_getpwnam($argv[1])) === FALSE) {
        fprintf(STDERR, "%s 用户不存在!\n", $argv[1]);
        return 0;
    }

    if (pcntl_fork() == 0) {
        putenv("HOME=".$user['dir']);
        putenv("USER=".$user['name']);
        putenv("USERNAME=".$user['name']);
        putenv("LOGNAME=".$user['name']);
        putenv("MAIL=/var/mail/".$user['name']);

        chdir($user['dir']);

        posix_initgroups($user['name'], $user['gid']);
        posix_setgid($user['gid']);
        posix_setuid($user['uid']);
        pcntl_exec($user['shell']);
        exit(0);
    }
    pcntl_wait($status);

    return 0;
}

exit(main($argc, $argv));

